package cn.bluethink.utile;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class HttpUtil {

    /**
     * 向指定URL发送GET方法的请求
     * @param url 发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) throws IOException {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            String requestUrl = new String(urlNameString.getBytes(),"utf-8");
            URLConnection connection = getConnection(requestUrl);
            // 建立实际的连接
            connection.connect();
            result = getRes(in,connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            if (in != null) {
                in.close();
            }
        }
        return result;
    }

    /**
     * 验证token 将token放在header
     * @param url
     * @param param
     * @return
     * @throws IOException
     */
    public static String authentication(String url, Map<String, String> param) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                builder.addParameter("userId", param.get("userId"));
                builder.addParameter("password", param.get("password"));
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            httpGet.addHeader("token",param.get("token"));
            // 执行请求
            response = httpclient.execute(httpGet);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null){
                response.close();
            }
        }
        return resultString;
    }


    /**
     * @param urlNameString
     * @return
     * @throws IOException
     */
    private static URLConnection getConnection(String urlNameString) throws IOException {
        URL realUrl = new URL(urlNameString);
        // 打开和URL之间的连接
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setRequestProperty("Content-Type","Content-type:text/html; charset=UTF-8");
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        return connection;
    }

    /**
     * 封装相应结果
     * @param in
     * @param connection
     * @return
     * @throws IOException
     */
    public static String getRes(BufferedReader in,URLConnection connection) throws IOException {
        String result = "";
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        return result;
    }
}
